package cn.idu.jvmtest

/**
 * 使用stop来强行终止线程容易导致数据不一致
 */
class User() {
    var id: Int = 0
    var name: String = "0"
}

val u = User()

class ChangeObjectThread : Thread() {
    override fun run() {

        while (true) {
            synchronized(u) {
                val v = (System.currentTimeMillis() / 1000).toInt()
                u.id = v
                sleep(100)
                u.name = v.toString()
            }
            yield()
        }
    }
}

class ReadObjectThread : Thread() {
    override fun run() {
        while (true) {
            synchronized(u) {
                if (u.id != u.name.toInt()) {
                    println("id:${u.id}  name:${u.name}")
                }
            }
            yield()
        }
    }
}


fun main(args: Array<String>) {
    print("main start")
    ReadObjectThread().start()

    while (true) {
        val t = ChangeObjectThread()
        t.start()
        Thread.sleep(100)
        t.stop()
    }
}